/*
 * Activiti Modeler component part of the Activiti project
 * Copyright 2005-2014 Alfresco Software, Ltd. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

/*
 * Assignment
 */
var KisBpmAssignmentCtrl = ['$scope', '$modal', function ($scope, $modal) {

	// Config for the modal window
	var opts = {
		template: window._server + 'editor-app/configuration/properties/assignment-popup.html?version=' + Date.now(),
		scope: $scope
	};

	// Open the dialog
	$modal(opts);
}];

var KisBpmAssignmentPopupCtrl = ['$scope', '$http', function ($scope,$http) {

	
           
            
            $scope.itemClicked = function ($item) {
                $scope.selectedItem = $item;
            };
    
            $scope.itemCheckedChanged = function($item){
                // $http.post('/url', $item);
            };
    
	// Put json representing assignment on scope
	if ($scope.property.value !== undefined && $scope.property.value !== null
		&& $scope.property.value.assignment !== undefined
		&& $scope.property.value.assignment !== null) {
		$scope.assignment = $scope.property.value.assignment;
	} else {
		$scope.assignment = {};
	}

	if ($scope.assignment.candidateUsers == undefined || $scope.assignment.candidateUsers.length == 0) {
		$scope.assignment.candidateUsers = [{ value: '' }];
	}

	// Click handler for + button after enum value
	var userValueIndex = 1;
	$scope.addCandidateUserValue = function (index) {
		$scope.assignment.candidateUsers.splice(index + 1, 0, { value: 'value ' + userValueIndex++ });
	};

	// Click handler for - button after enum value
	$scope.removeCandidateUserValue = function (index) {
		$scope.assignment.candidateUsers.splice(index, 1);
	};

	if ($scope.assignment.candidateGroups == undefined || $scope.assignment.candidateGroups.length == 0) {
		$scope.assignment.candidateGroups = [{ value: '' }];
	}

	var groupValueIndex = 1;
	$scope.addCandidateGroupValue = function (index) {
		$scope.assignment.candidateGroups.splice(index + 1, 0, { value: 'value ' + groupValueIndex++ });
	};

	// Click handler for - button after enum value
	$scope.removeCandidateGroupValue = function (index) {
		$scope.assignment.candidateGroups.splice(index, 1);
	};

    $scope.initData=function (data){

        for (var k = 0; k < data.length; k++) {

            if(data[k].childList){
                $scope.initData(data[k].childList)
            }

            data[k].$$isChecked = false;

        }
    }

    $scope.filterData = function (data){
		let idData = $scope.assignment.candidateGroups;
		for(var i=0;i<data.length;i++){
			if(data[i].childList){
				$scope.filterData(data[i].childList)
			}
			for (var k = 0; k < idData.length; k++) {
//				console.log(idData[k].value + ":" + data[i].data.id)
				if(idData[k].value == data[i].data.id){
					data[i].$$isChecked = true;
				}
			}
		}
	}
    $scope.initData($scope.treeData);
    $scope.filterData($scope.treeData);
    $scope.datas =$scope.treeData;

    $scope.ztree = function (arr,newArr){
		 newArr =newArr || [];
		for(var i=0; i<arr.length; i++){
			if(arr[i].childList){
				$scope.ztree(arr[i].childList,newArr);
			}
		// 	console.log(arr[i].$$isChecked);
			if(arr[i].$$isChecked){
				let obj = {};
				obj.value = arr[i].icon;
				newArr.push(obj);
			}		
		}
//		console.log(newArr)
		$scope.assignment.candidateGroups = newArr;

	}

	$scope.save = function () {


		$scope.property.value = {};
		handleAssignmentInput($scope);
		$scope.property.value.assignment = $scope.assignment;
		$scope.updatePropertyInModel($scope.property);
		$scope.close();
		$scope.selectfn()
		$scope.ztree($scope.datas);
	};

	// Close button handler
	$scope.close = function () {
		handleAssignmentInput($scope);
		$scope.property.mode = 'read';
		$scope.$hide();
	};
	

	$scope.filterData = function (){
		$scope.selectArr = [];
		$scope.selectDatas.forEach((val,idx)=>{
			let obj = $scope.assignment.candidateUsers
			if(obj){
				for(var i=0; i<obj.length;i++ ){
				if(val.id == obj[i].value){
					val.isShow = true;
					$scope.selectArr.push(val.strategyName);
				}else{
					val.isShow = false;
				}
			}
			}
			
		})
	}
	$scope.filterData();
	$scope.fn = function(s){
		if(s.isShow){
		   $scope.selectArr.push(s.strategyName); 
		}else{
			$scope.selectArr.forEach((val,idx)=>{
				if(val == s.strategyName){
					 $scope.selectArr.splice(idx,1)
				}
			})
		}
	}
	$scope.selectfn = function (){
		let newArr = [];
		$scope.selectDatas.forEach((val)=>{
			let obj = {};
			if(val.isShow){
				obj.value = val.id;
				newArr.push(obj);
			}
		})
		$scope.assignment.candidateUsers = newArr;
	}
	
	var handleAssignmentInput = function ($scope) {
		if ($scope.assignment.candidateUsers) {
			var emptyUsers = true;
			var toRemoveIndexes = [];
			for (var i = 0; i < $scope.assignment.candidateUsers.length; i++) {
				if ($scope.assignment.candidateUsers[i] != '') {
					emptyUsers = false;
				}
				else {
					toRemoveIndexes[toRemoveIndexes.length] = i;
				}
			}

			for (var i = 0; i < toRemoveIndexes.length; i++) {
				$scope.assignment.candidateUsers.splice(toRemoveIndexes[i], 1);
			}

			if (emptyUsers) {
				$scope.assignment.candidateUsers = undefined;
			}
		}

		if ($scope.assignment.candidateGroups) {
			var emptyGroups = true;
			var toRemoveIndexes = [];
			for (var i = 0; i < $scope.assignment.candidateGroups.length; i++) {
				if ($scope.assignment.candidateGroups[i].value != '') {
					emptyGroups = false;
				}
				else {
					toRemoveIndexes[toRemoveIndexes.length] = i;
				}
			}

			for (var i = 0; i < toRemoveIndexes.length; i++) {
				$scope.assignment.candidateGroups.splice(toRemoveIndexes[i], 1);
			}

			if (emptyGroups) {
				$scope.assignment.candidateGroups = undefined;
			}
		}
	};
	return  $scope;
}];
activitiModeler.directive('treeView',[function(){

    return {
        restrict: 'E',
        templateUrl: '/treeView.html',
        scope: {
            treeData: '=',
            canChecked: '=',
            textField: '@',
            itemClicked: '&',
            itemCheckedChanged: '&',
            itemTemplateUrl: '@'
        },
        controller:['$scope', function($scope){
            $scope.itemExpended = function(item, $event){
                item.$$isExpend = ! item.$$isExpend;
                $event.stopPropagation();
            };

            $scope.getItemIcon = function(item){
                var isLeaf = $scope.isLeaf(item);

                if(isLeaf){
                    return 'fa fa-leaf';
                }

                return item.$$isExpend ? 'fa fa-minus': 'fa fa-plus';	 
            };

            $scope.isLeaf = function(item){
                return !item.childList || !item.childList.length;
            };

            $scope.warpCallback = function(callback, item, $event){
                ($scope[callback] || angular.noop)({
                    $item:item,
                    $event:$event
                });
            };
        }]
	};
}]);